## package and enviroments:

library("pacman")
p_load("dplyr")
p_load("plyr")
p_load("ggplot2")
p_load("stringr")
p_load("reshape2")
p_load("PMCMR")
p_load("ggforce")
p_load(openxlsx)
p_load(Loafer)
get_or_set_dir()

# 
# {
#   input_df = each_df
#   # input_df$Sepal.Length <- rnorm(nrow(input_df)),
#   group_info_df = group_info
#   group_index = group_index_or_name
#   group_levels_in_order_C = group_info_df[,group_index] %>% unique()
#   test_pattern  = 'para'
#   # test_pattern  = 'wise' ,
#   # test_pattern  = 'non-para' %>% tolower(),
#   # choose one of the p value.
#   p_for_label = "pairwise_p.raw"
#   # p_for_label = "pairwise_p.adj",
#   step = 0.04 # Modify the vertical distances between significant label codes.
# 
#   draw_pics = F
#   unify_step_as_constant = F
#   position_by = 'max meanse'
#   get_step_by_max_instead_of_range = T
#   
#   
#   p_for_label = "p_all"
#   group_levels_in_order_C = c("WT+BCAAs", "KO+BCAAs")
#   
# }

{
  ## Input parameters：
  input_file_name <- "P081Y21 数据 for 代谢流.xlsx"
  group_index_or_name <- 1 ## group col index in numeric or groupname in character.
  
  ## get_original data
  df <- read.xlsx(input_file_name, sheet = 2)
  df %>% head
  group_info <- read.xlsx(input_file_name, sheet = 3) %>% nth_col_as_rowname()
  group_info <- group_info[,group_index_or_name, drop = F]
  group_info %>% head
}

{
  block_ends <- (df$X1 == "Fractional contribution") %>% which()
  block_counts <- length(block_ends)
  block_starts <- c(1, block_ends[-block_counts] + 1)
  
  for(i in 1:block_counts){
    temp_df <- df[block_starts[i]:(block_ends[i]),]   
    each_df <- temp_df %>% nth_col_as_rowname() %>% t %>% data.frame(., stringsAsFactors = F, check.names = F)
    
    each_meta <- colnames(each_df) %>% `[`(., 1)
    number_in_row <- ncol(each_df)
    
    obj <- get_pic_with_labels(input_df = each_df,
                               # input_df$Sepal.Length <- rnorm(nrow(input_df)),
                               group_info_df = group_info,
                               group_index = group_index_or_name,
                               group_levels_in_order_C = group_info[,group_index_or_name] %>% unique(),
                               # group_levels_in_order_C = c("WT+BCAAs", "KO+BCAAs"),
                               test_pattern  = 'para' ,
                               # test_pattern  = 'wise' ,
                               # test_pattern  = 'non-para' %>% tolower(),
                               # choose one of the p value.
                               p_for_label = "pairwise_p.raw",
                               # p_for_label = "pairwise_p.adj",
                               # p_for_label = "p_all",
                               step = 0.04, # Modify the vertical distances between significant label codes.
                               
                               draw_pics = F, 
                               unify_step_as_constant = F,
                               position_by = 'max meanse')   
    # obj@label_position_df$label.y
    p <- obj@result_df$p_for_label
    
    variables_c <- obj@pic_long_df$variable %>% unique
    
    page_num <- variables_c %>% length
    segment_size <- .7 ## The size of the segement
    
    obj@pic_long_df %>% head
    
    pic <- ggplot(obj@pic_long_df) + 
      ## error bar by mean ± se
      geom_errorbar( aes(x= group, ymin=mean-se, ymax=mean+se),  
                     width=0.4, colour='black', alpha=0.9, size=1.3) +
      geom_bar(aes(x = group, y = mean, group = group, fill = group), data = obj@pic_long_df , 
               # size  = .8,
               position = position_dodge(),
               stat='identity'
               # outlier.colour = 'white',
               # width = 2,
               
      )+
      xlab(NULL)+
      ylab('Fraction')+
      scale_y_continuous(expand = expansion(c(0.0,0.05)))+
      
      theme_bw()+
      facet_wrap(facets = vars(variable), nrow = 1, scales = 'free_y')+
      theme(
        text = element_text(size = 18, color = 'black'),
        axis.text.y = element_text( size = 12, face = 'bold', color = 'black'),
        axis.text.x = element_text( size = 12, face = 'bold', color = 'black', angle = 90),
        strip.background=element_rect(size=20, color = "grey80"),
        strip.text.x = element_text(size = 16, color = 'black'),
        legend.position = "bottom",
        panel.background = element_rect(fill = "white", colour = "grey50", size = .7),
        panel.grid = element_blank()
      )
    # pic
    if(nrow(obj@label_position_df) > 0 ){
      ### If there is any labels(significant changes between groups), then visualize it.
      obj@label_position_df$variable
      pic <- pic +
        # geom_segment(data = obj@label_position_df,
        #              aes(x = start_num, xend = start_num + 0.25 * (end_num - start_num),
        #                  y = label.y, yend = label.y), lineend = 'butt', size = segment_size)+
        # geom_segment(data = obj@label_position_df, 
        #              aes(x = end_num, xend = start_num + 0.75 * (end_num - start_num),
        #                  y = label.y, yend = label.y), 
        #              lineend = 'butt', size = segment_size)+
        geom_text(data = obj@label_position_df, 
                  aes(x = 0.5 *(start_num + end_num), y = label.y*1.006, label = label)
                  ,color = 'black', size = 8) +
        geom_segment(data = obj@label_position_df,
                     aes(x = start_num, xend = start_num, 
                         y = label.y, yend = label.y * .995), 
                     lineend = 'round', size = segment_size)+
        geom_segment(data = obj@label_position_df, aes(x = end_num, xend = end_num, 
                                                       y = label.y, yend = label.y * .995), 
                     lineend = 'round', size = segment_size)+
        geom_segment(data = obj@label_position_df, aes(x = start_num, xend = end_num, 
                                                       y = label.y, yend = label.y),
                     size = segment_size) 
      
    }
    
    # pic
    
    { ## output the results.
      plot_name <- sprintf('%splot with sig labels #%s.pdf',output_path, each_meta)
      csv_name <- plot_name %>% sub(".pdf$", ".csv", .)
      ggsave(plot_name, plot = pic, width = number_in_row * 3.7, height = 10, 
             limitsize = F, family = 'serif')
      obj@result_df %>% write.csv(., csv_name, row.names = F)
    }
    
  }
}
